package com.xyh.jdk8Demo;

import javax.sound.midi.Soundbank;

/**
 * @version v1.0
 * @类描述： 测试Thredlocal是不是每个线程都存在
 * @项目名称：
 * @包名： com.xyh.jdk8Demo
 * @类名称：DemoThred
 * @创建人：YIHANG.XU
 * @创建时间：2020/6/43:49 下午
 * @修改人：YIHANG.XU
 * @修改时间：2020/6/43:49 下午
 * @修改备注：
 * @Copyright
 */
public class DemoThred {
    static ThreadLocal<String> local = new ThreadLocal<>();

    public static void setLocalKey(String name) {
        local.set(name);
    }

    public static String getLoaclKey() {
        return local.get();
    }

    public static void main(String[] args) {
        System.out.println("主线程开始运行");
        System.out.println("开始设置参数");
        setLocalKey("我是主线线程的参数");
        Thread sss = new Thread(new aaa());
        sss.setName("xiancheng1");
        sss.start();

        Thread ddd = new Thread(new bbb());
        ddd.setName("xiancheng2");
        ddd.start();

        try {
            Thread.sleep(1000000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程获取值");
        String loaclKey = getLoaclKey();
        System.out.println(loaclKey);
        System.out.println("主线程执行完成");
    }

    static class aaa implements Runnable {
        @Override
        public void run() {
            System.out.println("线程1 开始运行");
            System.out.println("线程1 获取值");
            String loaclKey = getLoaclKey();
            setLocalKey("我是线程一号参数");
            System.out.println(loaclKey);
            try {
                Thread.sleep(400000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("获取值");
            System.out.println(getLoaclKey());
            System.out.println("线程1 执行完成");
        }
    }

    static class bbb implements Runnable {
        @Override
        public void run() {
            System.out.println("线程2 开始运行");
            System.out.println("线程2 获取值");
            String loaclKey = getLoaclKey();
            setLocalKey("我是线程2");
            System.out.println(loaclKey);
            try {
                Thread.sleep(400000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("获取值");
            System.out.println(getLoaclKey());
            System.out.println("线程2线程执行完成");
        }
    }
}
